import { useEffect, useRef, useState, useCallback } from 'react';
import { CanvasManager } from '../../draw/canvas-manager';
import ControlPanel from '../ControlPanel';
import PropertyPanel from '../PropertyPanel';
import styles from './index.module.less';
import { stateManager } from '../../draw/state-manager';
import type { DrawingMode, CanvasState } from '../../draw/types';
import type { ShapeProperties } from '../../draw/shapes/Shape';

export function Drawboard() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const canvasManagerRef = useRef<CanvasManager | null>(null);

  const [mode, setMode] = useState<DrawingMode>('select');
  const [color, setColor] = useState('#0000ff');
  const [lineWidth, setLineWidth] = useState(1);
  const [properties, setProperties] = useState<ShapeProperties | null>(null);
  const [cursorPosition, setCursorPosition] = useState<{ x: number; y: number } | undefined>(undefined);

  const resetView = () => {
    canvasManagerRef.current?.resetView();
  };

  const clearCanvas = () => {
    canvasManagerRef.current?.clearCanvas();
  };

  const handlePropertyChange = (property: string, value: string) => {
    canvasManagerRef.current?.updateShapeProperty(property, value);
  };

  // 同步模式到stateManager
  const handleModeChange = (newMode: DrawingMode) => {
    setMode(newMode);
    stateManager.setMode(newMode);
  };

  // 同步颜色到stateManager
  const handleColorChange = (newColor: string) => {
    setColor(newColor);
    stateManager.setStrokeColor(newColor);
  };

  // 同步线宽到stateManager
  const handleLineWidthChange = (newLineWidth: number) => {
    setLineWidth(newLineWidth);
    stateManager.setStrokeWidth(newLineWidth);
  };

  // 更新属性面板
  const updateProperties = useCallback(() => {
    const selectedShape = stateManager.getSelectedShape();
    if (selectedShape) {
      setProperties(selectedShape.getProperties());
    } else {
      setProperties(null);
    }
  }, []);

  useEffect(() => {
    if (canvasRef.current) {
      const canvas = canvasRef.current;
      canvasManagerRef.current = new CanvasManager({ 
        canvas, 
        stateManager,
        onCursorPositionChange: setCursorPosition
      });

      // 添加状态变化监听器
      const handleStateChange = (state: CanvasState) => {
        if (state.selectedShape) {
          setProperties(state.selectedShape.getProperties());
        } else {
          setProperties(null);
        }
      };

      stateManager.onStateChange = handleStateChange;

      const handleResize = () => {
        if (canvasRef.current) {
          canvasRef.current.width = window.innerWidth;
          canvasRef.current.height = window.innerHeight;
          canvasManagerRef.current?.draw();
        }
      };

      window.addEventListener('resize', handleResize);

      return () => {
        window.removeEventListener('resize', handleResize);
        stateManager.onStateChange = undefined;
        canvasManagerRef.current?.cleanup();
      };
    }
  }, [updateProperties]);

  return (
    <div className={styles['drawboard-container']}>
      <canvas
        ref={canvasRef}
        width={window.innerWidth}
        height={window.innerHeight}
        style={{ border: '1px solid #000', width: '100%', height: '100%', backgroundColor: '#1a1a1a' }}
      />
      <ControlPanel
        mode={mode}
        color={color}
        lineWidth={lineWidth}
        cursorPosition={cursorPosition}
        onModeChange={handleModeChange}
        onColorChange={handleColorChange}
        onLineWidthChange={handleLineWidthChange}
        onResetView={resetView}
        onClearCanvas={clearCanvas}
      />
      <PropertyPanel
        properties={properties}
        onPropertyChange={(property, value) => {
          setProperties((prev) => {
            return {
              ...(prev ? prev : {}),
              [property]: value,
            } as ShapeProperties;
          });
          handlePropertyChange(property, value as string);
        }}
      />
    </div>
  );
}
